package com.mud.dnd.frontend.rs;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.mud.dnd.domain.common.DAOException;
import com.mud.dnd.domain.common.QueryParameter;
import com.mud.dnd.domain.common.QueryParameter.QueryParamOperator;
import com.mud.dnd.domain.model.Card;
import com.mud.dnd.domain.model.Comment;
import com.mud.dnd.ejb.CommentManager;
import com.mud.dnd.ejb.common.AuthenticationException;
import com.mud.dnd.frontend.rs.common.RestInputConverter;

@Stateless
@Path("/GameItem/Comment")
public class CommentJSONService {

	@EJB
	CommentManager ejbService;
	
	
	@GET
	@Path("/query")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Comment> getComments(@QueryParam("id") Integer id,@QueryParam("gameItemID") Integer gameItemID,@QueryParam("message") String message,@QueryParam("userName")String userName) {
		
		
		List<QueryParameter> params = new ArrayList<QueryParameter>();
		try{
		
		
		if(id!=null)
		{
			params.add(new QueryParameter("id", QueryParamOperator.EQUALS, id));
		}
		if(message!=null)
		{
			params.add(new QueryParameter("name", QueryParamOperator.LIKE, message));
		}
		if(gameItemID!=null)
		{
			params.add(new QueryParameter("gameItemID", QueryParamOperator.EQUALS, gameItemID));
		}
		
		if(userName!=null)
		{
			params.add(new QueryParameter("author", QueryParamOperator.LIKE, userName));
		}
		
		}catch(DAOException e)
		{
			return null;
		}
		

 
		return ejbService.getComments(params); 
 
	}
	
	@GET
	@Path("/add")
	@Produces(MediaType.APPLICATION_JSON)
	public String addComment(@QueryParam("gameItemID") int gameItemID,@QueryParam("message") String message,@QueryParam("userName") String userName,@QueryParam("sessionID") String sessionID)
	{
		int resultID = 0;
		
		try {
			resultID = ejbService.addComment(message, userName, gameItemID, sessionID);
		} catch (DAOException e) {
			return "ERROR: "+e.getMessage();
		} catch (AuthenticationException e) {
			return "ERROR: "+e.getMessage();
		}
		return "OK new comment id:"+resultID;
	}
	
	@GET
	@Path("/delete")
	@Produces(MediaType.APPLICATION_JSON)
	public String deleteComment(@QueryParam("id")int commentID,@QueryParam("userName")String userName,@QueryParam("sessionID")String sessionID)
	{
		try {
			ejbService.deleteComment(commentID, userName, sessionID);
		} catch (DAOException e) {
			return "ERROR: "+e.getMessage();
		} catch (AuthenticationException e) {
			return "ERROR: "+e.getMessage();
		}
		
		return "OK";
	}
}
